<template>
	<div class="train_date train">
		<div class="train_dateHeader">
			<header class="train_date_header">
				<p>选择日历</p>
				<div @click="clickReturn">
					<img src="../../../assets/train/rili-guanbi@2x.png"/>
				</div>
				<span v-if="alternative" @click="submit">确定</span>
			</header>
			<div class="train_tip" v-if="!isChangTicket && !alternative">{{advanceDate.trainTips}}</div>
		</div>
		<div class="train_date_zhan" :class="{'active':(isChangTicket || alternative)}"></div>
		<!--日历-->
		<div class="train_data_content">
			<div v-for="item in dateArr" class="train_data_mouth">
				<div class="train_data_mouth_msg">{{item.mouth}}</div>
				<div class="train_data_day week">
					<div v-for="item in weekday">
						<div class="train_data_everyday">{{item}}</div>
					</div>
				</div>
				<div class="train_data_day">
					<div v-for="val in item.firstWeek" style="height: 0;"></div>
					<div v-for="val in item.day">
						<div class="train_data_everyday" :class="{'gray':val.isGray,'active':val.isAcitve}" @click="chooseDate(val)">
							<span v-if="val.isToday">今天</span>
							<span v-else>{{val.dateDay}}</span>
							<span v-if="val.isAcitve && alternative" class="train_date_rob active">多选</span>
							<template v-else>
								<span v-if="!val.isGray && val.isRob" class="train_date_rob">抢</span>
							</template>
						</div>
					</div>
					<div v-for="item in weekday" style="height: 0;"></div>
				</div>
			</div>
		</div>
	</div>
</template>
<style scoped>
	.train_date {
		background: #fff;
	}
	
	.train_date > .train_dateHeader {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		z-index: 52;	
		background: #fff;	
	}
	
	.train_date_zhan {
		height: 150px;
	}
	
	.train_date_zhan.active {
		height: 90px;
	}
	
	.train_date_header {
		height: 100px;
		display: flex;
		justify-content: center;
		align-items: center;
		font-size: 32px;
		color: #333333;
		position: relative;
		top: 0;
		left: 0;
	}
	
	.train_date_header>div {
		width: 44px;
		height: 100%;
		position: absolute;
		left: 30px;
		top: 0;
		display: flex;
		align-items: center;
	}
	
	.train_date_header>div>img {
		width: 100%;
		height: 44px;
	}
	
	.train_date_header>span {
		width: 80px;
		height: 100%;
		position: absolute;
		right: 30px;
		top: 0;
		display: flex;
		align-items: center;
		font-size: 30px;
		color: #3bc3c2;
	}
	
	.train_tip {
		font-size: 28px;
		color: #fb6523;
		background-color: #FFE7DD;
		width: 100%;
		display: flex;
		justify-content: flex-start;
		align-items: center;
		padding: 15px 20px;
		box-sizing: border-box;
		line-height: 35px;
	}
	
	.train_data_content {
		padding: 24px 36px;
	}
	
	.train_data_mouth {
		width: 100%;
		margin-top: 44px;
		text-align: center;
		font-size: 32px;
	}
	
	.train_data_mouth_msg {
		margin-bottom: 43px;
	}
	
	.train_data_day {
		display: flex;
		justify-content: space-between;
		flex-wrap: wrap;
	}
	
	.train_data_day.week {
		font-size: 22px;
	}
	
	.train_data_day > div {
		width: 14.285714285714286%;
		height: 70px;
		display: flex;
		justify-content: center;
		align-items: center;
		margin: 5px 0;
	}
	.train_data_everyday {
		width: 75px;
		height: 100%;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		color: #000;
		font-size: 26px;
		border-radius: 8px;
	}
	
	.train_data_everyday.gray{
		color: #999;	
	}
	
	.train_data_everyday.active{
		background-color: #52C9C8;	
		font-size: 28px;
		color: #fff;
	}
	
	.train_date_rob {
		color:rgb(251,101,35); 
		font-size: 20px;
	}
	
	.train_date_rob.active {
		color: #fff;
	}
</style>
<script>
	export default {
		data() {
			return {
				dateAllDays: 60, //日历的总天数（今天开始往后多少天）	
				dateArr: [], //存日历对象
				weekday:["日","一","二","三","四","五","六"],
				departureDate:"",//当前日期
				advanceDate:{},//预售
				isChangTicket:false,//是否为改签
				alternative:false,//是否为抢票预售
				alternativeDateArr:[],//选中的日历
				fillOrder:null,//订单页
			}
		},
		created() {
			
		},
		mounted() {
			this.departureDate =  this.$route.query.departureDate || new Date().format("yyyy-MM-dd");
			this.isChangTicket = Number(this.$route.query.isChangTicket) ? true : false;
			this.alternative = Number(this.$route.query.alternative);//是否为抢票预售
			(this.alternative) && (this.fillOrder = JSON.parse(JSON.stringify(this.$store.state.train.trainStore.fillOrder)));//订单页变量
			(this.alternative) && this.alternativeDateArr.push(...this.fillOrder.alternative.date);
			if (this.$store.state.train.trainStore.advanceDate) {
				this.advanceDate = this.$store.state.train.trainStore.advanceDate;//预售
				this.dateAllDays = this.isChangTicket ? Number(this.advanceDate.trainAdvanceDays) : Number(this.advanceDate.dayNum);
				this.dateArr = this.getDate(this.dateAllDays,this.departureDate);
			} else {
				this.advanceBook();
			};
		},
		methods: {
			getDate(dateAllDays,departureDate) { //构建日历 传入未来所需要的天数
				let endDate = this.$publicMethod.getNowFormatDateAfter(dateAllDays - 1); //结束日期
				let dateArr = []; //构建日历数组
				let firstDay = new Date(new Date().setDate(1)); //获取当月的第一天
				let disMouth = (endDate.getFullYear() * 12 + endDate.getMonth()) - (firstDay.getFullYear() * 12 + firstDay.getMonth()) + 1; //计算相差月数
				let num = 0;//计数器
				//循环构建日历
				for(var i = 0; i < disMouth; i++) {
					let flag = true;
					let nowDay = firstDay; //当前天
					let arr = [this.plantDate(nowDay, endDate, departureDate, num)];
					(nowDay.format("yyyy-MM-dd") == new Date().format("yyyy-MM-dd")) && (num++);
					let arrObj = {}; //当月对象
					while(flag) {
						var day = this.$publicMethod.getNowFormatDateAfter(1, nowDay.format("yyyy-MM-dd")); //获取后一天
						num ? (num ++ ) : (((day.getTime() > new Date().getTime()) || (day.format("yyyy-MM-dd") == new Date().format("yyyy-MM-dd"))) && (num++));
						var dayMouth = day.getMonth() + 1; //后一天的月
						var nowDayMouth = nowDay.getMonth() + 1; //前一天的月
						(dayMouth == nowDayMouth) ? (arr.push(this.plantDate(day, endDate, departureDate, num)) && (nowDay = day)) : ((firstDay = day) && (flag = false));
					};
					arrObj.mouth = arr[0].dateMsg.format("yyyy.MM"); //年月
					arrObj.firstWeek = arr[0].dateMsg.getDay(); //第一天是周几
					arrObj.day = arr; //年月
					dateArr.push(arrObj);
				};
				return dateArr;
			},
			plantDate(day, endDate, departureDate, num) { //工厂模式组装日历
				/*
				 *  param:
				 * 
				 *  day  日历对象
				 * 
				 *  endDate 结束时间,
				 * 
				 * 	departureDate 选中日期
				 * 
				 * 	num 预约抢票计数天数
				 * 
				 * */
				let weekday = new Array("周日", "周一", "周二", "周三", "周四", "周五", "周六"); //创建星期数组
				//计算置灰
				Array.isArray(departureDate) || (departureDate = new Array(departureDate));
				this.alternativeDateArr.forEach((val)=>{
					departureDate.push(val.dateStr);
				});
				let isToday = day.format("yyyy-MM-dd") == new Date().format("yyyy-MM-dd");
				let flag = this.$publicMethod.isDateBetween(day.format("yyyy-MM-dd"), new Date().format("yyyy-MM-dd"), endDate.format("yyyy-MM-dd"));
				var dateObj = { //此处组装日历所需要的数据
					dateMsg: day,
					dateStr: day.format("yyyy-MM-dd"), //年月日
					dateStrMsg: day.format("MM月dd日"), //月日
					dateDay: Number(day.format("dd")), //天
					dateWeek: weekday[day.getDay()], //周几
					isToday: isToday, //是否为今天
					isGray: !(flag || isToday), //是否置灰
					isAcitve:false,//是否高亮
					isRob:num > this.advanceDate.trainQPvanceDays,//是否展示抢字
					isDepartureDate:false,//是否为主日期（抢票用）
				};
				departureDate.forEach((val,index)=>{
					(val == dateObj.dateStr) && (dateObj.isAcitve = true);
					(val == dateObj.dateStr && !index) && (dateObj.isDepartureDate = true); 
				});
				return dateObj;
			},
			clickReturn() { //回退	
				this.$router.go(-1);
			},
			chooseDate(val){
				if (val.isGray) return;
				if(this.alternative) {//抢票多选日期  //主日期不操作
					val.isDepartureDate || (val.isAcitve ? ((val.isAcitve = false) || splice(val,this)) : (this.alternativeDateArr.length > 4) ? this.$toast("最多可以选择5个日期哦", {
						durtaion: 200,
						location: 'center',
					}) : ((val.isAcitve = true) && this.alternativeDateArr.push(val)));
					function splice(val,that){ //剔除
						var index = -1;
						that.alternativeDateArr.forEach((item,key)=>{
							(item.dateStr == val.dateStr) && (index = key);
						});
						(index > -1) && that.alternativeDateArr.splice(index,1);
					};
				} else { //普通
					var trainStore = JSON.parse(JSON.stringify(this.$store.state.train.trainStore));
					(this.isChangTicket) ? (trainStore.changeMessage.departureDate = val.dateStr) : (trainStore.departureDate = val.dateStr);//是否改签
					this.$store.commit('TRAINSTORE', trainStore);
					this.$router.go(-1);	
				};
			},
			submit(){//提交（抢票）
				var dateStr = this.fillOrder.msg.saleDateTime.split(" ")[0];
				if(this.alternativeDateArr.length) { //选了
					this.alternativeDateArr.sort(function(a,b){ //日期排序
						return new Date(a.dateMsg).getTime() - new Date(b.dateMsg).getTime();
					});
					var getTime = new Date(this.fillOrder.departureDate.replace(/-/g,"/")).getTime() - new Date(this.alternativeDateArr[0].dateStr).getTime();
					dateStr = new Date(new Date(dateStr.replace(/-/g,"/")).getTime() - getTime).format("yyyy-MM-dd");
				};
				this.fillOrder.alternative.date = this.alternativeDateArr; //备选日期
				var maxDepartTime = new Date(this.alternativeDateArr[this.alternativeDateArr.length-1].dateMsg).getTime() - new Date(this.departureDate.replace(/-/g,"/")).getTime() > 0 ? this.alternativeDateArr[this.alternativeDateArr.length-1].dateStr : this.departureDate;
				maxDepartTime = maxDepartTime + " " + this.fillOrder.maxDepartTime.split(" ")[1];
				this.fillOrder.maxDepartTime = maxDepartTime;//计算最晚发车时间
				var minTime = dateStr + " " + this.fillOrder.minTime.split(" ")[1];
				this.fillOrder.minTime = minTime;//计算抢票开始时间
				//更新上个页面变量
				var trainStore = JSON.parse(JSON.stringify(this.$store.state.train.trainStore));
				trainStore.fillOrder = this.fillOrder;
				this.$store.commit('TRAINSTORE', trainStore);
				this.$router.go(-1);
			},
			advanceBook() { //预售查询
				this.$http.post(this.$baseUrl.baseurl + "tctrain/train/trainAdvanceTime", {}).then((res) => {
					var data = res.data.Result;
					var dayNum = Number(data.trainAdvanceDays) + Number(data.trainQPvanceDays);
					//替换@
					data.trainGQTips = data.trainGQTips.replace(/@/g, data.trainAdvanceDays);
					data.trainTips = data.trainTips.replace(/@/g, data.trainQPvanceDays);
					//存全局
					var trainStore = JSON.parse(JSON.stringify(this.$store.state.train.trainStore));
					trainStore.advanceDate = data;
					trainStore.advanceDate.dayNum = dayNum;
					trainStore.advanceDate.date = data.trainQPAdvanceTime;
					trainStore.advanceDate.dateChange = data.advanceTime;
					this.$store.commit('TRAINSTORE', trainStore);
					this.advanceDate = this.$store.state.train.trainStore.advanceDate;//预售
					this.dateAllDays = this.isChangTicket ? Number(this.advanceDate.trainAdvanceDays) : Number(this.advanceDate.dayNum);
					this.dateArr = this.getDate(this.dateAllDays,this.departureDate);
				}).catch((err) => {
					console.log(err);
				});
			},
		},
		watch: { //监听放置

		},
		filters: { //过滤

		},
		components: {},
		computed: {}
	};
</script>